package ahjava.io;
import java.io.*;
import java.nio.IntBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class NIO03RW {
	static int TIMES = 500000;
	static long start = 0;
	static long end = 0;
	public static void main(String[] args) throws IOException {
		byStream();
		byByteBuffer();
	}
	static void byStream() throws IOException {
		start = System.currentTimeMillis();
		FileOutputStream fos = new FileOutputStream("D:\\byStream.txt");
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		DataOutputStream dos = new DataOutputStream(bos);
		for (int i = 0; i < TIMES; i++) {
			dos.writeInt(i);
		}
		dos.close();
		// --------------------------
		FileInputStream fis = new FileInputStream("D:\\byStream.txt");
		BufferedInputStream bis = new BufferedInputStream(fis);
		DataInputStream dis = new DataInputStream(bis);
		for (int i = 0; i < TIMES; i++) {
			dis.readInt();
		}
		dis.close();
		end = System.currentTimeMillis();
		System.out.println("byStream:" + (end - start));
	}
	static void byByteBuffer() throws IOException {
		String fileName = "D:\\byMap.txt";
		start = System.currentTimeMillis();
		RandomAccessFile ra = new RandomAccessFile(fileName, "rw");
		FileChannel channelW = ra.getChannel();
		MappedByteBuffer mapW = channelW.map(FileChannel.MapMode.READ_WRITE, 0,
				TIMES * 4);
		IntBuffer ibW = mapW.asIntBuffer();
		for (int i = 0; i < TIMES; i++) {
			ibW.put(i);
		}
		channelW.close();
		ra.close();
		// --------------------------
		FileInputStream fis = new FileInputStream("D:\\byMap.txt");
		FileChannel channelR = fis.getChannel();
		MappedByteBuffer mapR = channelR.map(FileChannel.MapMode.READ_ONLY, 0,
				channelR.size());
		IntBuffer ibR = mapR.asIntBuffer();
		while (ibR.hasRemaining()) {
			ibR.get();
		}
		channelR.close();
		fis.close();
		end = System.currentTimeMillis();
		System.out.println("byMap:" + (end - start));
	}
}
